<template>
  <div class="container">
    <!-- 搜索关键词展示 -->
    <div class="search-info" v-if="searchQuery">
      搜索关键词："{{ searchQuery }}"
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="loader"></div>
      正在加载中...
    </div>

    <!-- 错误提示（优化后的样式） -->
    <div v-else-if="error" class="error-card">
      <span class="error-icon">⚠️</span>
      {{ error }}
    </div>

    <!-- 商品列表 -->
    <template v-else>
      <div v-if="products.length === 0" class="empty-state">
        <img src="@/assets/empty-box.png" alt="空状态" class="empty-image">
        <p>没有找到相关商品</p>
      </div>

      <div v-else class="products-grid">
<!--        <div-->
<!--            v-for="product in products"-->
<!--            :key="product.id"-->
<!--            class="product-card"-->
<!--            @click="viewProductDetail(product.id)"-->
<!--        >-->
          <RouterLink
              v-for="product in products"
              :key="product.id"
              class="product-card"
              :to="`/detail/${product.id}`"
          >
          <img
              :src="product.picture"
              :alt="product.name"
              class="product-image"
              loading="lazy"
          >
          <div class="product-info">
            <h3 class="product-name">{{ product.name }}</h3>
            <!-- 显示商品描述 -->
            <p v-if="product.desc" class="product-desc">{{ product.desc }}</p>
            <div class="price-section">
              <!-- 价格格式化处理 -->
              <span class="product-price">
                ¥{{ parseFloat(product.price).toFixed(2) }}
              </span>
              <!-- 显示销量 -->
              <span class="product-sales">
                已售 {{ product.orderNum }} 件
              </span>
            </div>
          </div>
        </RouterLink>
      </div>
    </template>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getSearch } from "@/apis/search"

export default {
  setup() {
    const route = useRoute()
    const router = useRouter()
    const searchQuery = ref('')
    const products = ref([])
    const loading = ref(true)
    const error = ref('')

    // 获取商品数据（带参数传递）
    const fetchProducts = async () => {
      try {
        loading.value = true
        error.value = ''

        // 发送请求时携带搜索关键词
        const response = await getSearch(searchQuery.value)

        // 处理不同状态码
        switch (response.code) {
          case 200:
            // 数据转换处理
            products.value = response.data.map(product => ({
              ...product,
              price: parseFloat(product.price),  // 转换为数字
              orderNum: parseInt(product.orderNum) // 转换为整数
            }))
            break
          case 404:
            error.value = '搜索结果不存在'
            break
          default:
            throw new Error(response.message || '请求失败')
        }
      } catch (err) {
        error.value = `加载失败: ${err.message}`
        console.error('搜索请求失败:', err)
      } finally {
        loading.value = false
      }
    }

    // 初始化加载
    onMounted(async () => {
      searchQuery.value = (route.query.query || '').trim()

      // 增强的空值检查（包含空白字符处理）
      if (!searchQuery.value) {
        error.value = '请输入有效的搜索关键词'
        loading.value = false
        return
      }

      await fetchProducts()
    })

    // 查看商品详情
    const viewProductDetail = (productId) => {
      router.push(`/product/${productId}`)



    }

    return {
      searchQuery,
      products,
      loading,
      error,
      viewProductDetail
    }
  }
}
</script>

<style scoped>
/* 容器样式 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: 60vh;
}

/* 搜索信息 */
.search-info {
  font-size: 1.2rem;
  color: #666;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #eee;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.loader {
  display: inline-block;
  width: 30px;
  height: 30px;
  border: 3px solid #f3f3f3;
  border-radius: 50%;
  border-top-color: #3498db;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 错误提示 */
.error-card {
  padding: 2rem;
  background: #fff5f5;
  border: 1px solid #ffd6d6;
  border-radius: 8px;
  text-align: center;
  color: #dc3545;
  margin: 2rem 0;
}

.error-icon {
  font-size: 2rem;
  display: block;
  margin-bottom: 1rem;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 4rem 0;
}

.empty-image {
  width: 150px;
  opacity: 0.6;
  margin-bottom: 1rem;
}

/* 商品网格布局 */
.products-grid {
  display: grid;
  gap: 1.5rem;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
}

/* 商品卡片样式 */
.product-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.product-image {
  width: 100%;
  height: 240px;
  object-fit: contain;
  background: #f8f8f8;
  padding: 1rem;
}

.product-info {
  padding: 1.2rem;
}

.product-name {
  font-size: 1rem;
  line-height: 1.4;
  margin-bottom: 0.8rem;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-desc {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 1rem;
  line-height: 1.4;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.price-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  color: #e4393c;
  font-size: 1.2rem;
  font-weight: bold;
}

.product-sales {
  font-size: 0.9rem;
  color: #999;
}
</style>